// ActionScript file
import Modules.NavigationInfo;
import Modules.PostLogin;
import Modules.Windows.CMDWindow;

import com.desidea.common.CommonClass;
import com.desidea.common.MenuConstants;
import com.desidea.components.grid.button.SuperGridButton;
import com.desidea.utils.DirtyChecker;
import com.desidea.utils.IDirtyChecker;
import com.desidea.webservice.PartnerService;
import com.desidea.webservice.ProcessServiceRequestResultEvent;

import mx.controls.Alert;
import mx.controls.LinkButton;
import mx.core.Application;
import mx.events.ValidationResultEvent;
import mx.rpc.events.FaultEvent;
import mx.utils.StringUtil;

private var _btnEditCancel:LinkButton;

private var _key:String = "";
private var _mode:String = "view";//Constants.MODE_ADD;
private var _modeSet:Boolean = false;
private var _creationCompleted:Boolean = false;
private var actdetails:XML;
private var _accountGUID:String = "";

public function get mode():String{
	return _mode;
}

public function set mode(value:String):void{
	this._mode = value;
	this._modeSet = true;
	
//	setScreenMode();
//	this.loadData();
}

public function get key():String{
	return _key;
}

public function set key(value:String):void{
	this._key = value;
}

public function get accountGUID():String{
	return _accountGUID;
}

public function set accountGUID(value:String):void{
	this._accountGUID = value;
}

private function typeSelectionChange():void{
	cmbContact.dataProvider = actdetails.CONTACTS.entry.(@accountid == cmbAccountName.selectedItem.@id) as XMLList;
	cmbContact.selectedIndex = 0;
	cmbContact.selectedItem = (actdetails.CONTACTS.entry.(@id == actdetails.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT"))[0]) as XML
}

private function init():void{
	this.txtNotes.linkTextInput.visible = false;
	this.txtNotes._RichTextEditor_VRule2.visible = false;
}

private function setScreenMode():void{
	if(!_creationCompleted) return;
	
	if(this.mode == SuperGridButton.MODE_VIEW || mode == SuperGridButton.MODE_VIEWICON){
		frmActivityInfo.enabled = false;
		btnSubmit.enabled = false;
		cmbAccountName.selectedItem = (actdetails.ACCOUNTS.entry.(@id == actdetails.RELATIONS.RELATION.(@type == "ACTIVITY_ACCOUNT"))[0]) as XML;
		this.lblTitle.text = "View Activity Details";
	}else if(this.mode == SuperGridButton.MODE_EDIT){		//MODE_EDIT = create new
		frmActivityInfo.enabled = true;
		btnSubmit.enabled = true;
		_btnEditCancel.enabled = false;
		
		cmbAccountName.enabled = true;
		cmbActivityOwner.enabled = false;
		cmbActivityOwner.selectedItem = (actdetails.USERS.entry.(@id == CommonClass.UserID.toString())[0]) as XML;
		this.lblTitle.text = "New Activity";
	}
}

private function windowCreated():void{
	_btnEditCancel = new LinkButton();
	_btnEditCancel.label = "Edit";	
	_btnEditCancel.height = this.pnlActivityInfo.ToolBox.height - 2;
	_btnEditCancel.addEventListener(MouseEvent.CLICK, function(event:Event):void{ onClick('editdetails'); });
	this.pnlActivityInfo.ToolBox.addChild(_btnEditCancel);
	this._creationCompleted = true;
	this.loadData();
}

private function loadData():void{
	if( DirtyChecker.getInstance().isDirty){
		if (DirtyChecker.getInstance().sourceContainer is IDirtyChecker){
			(DirtyChecker.getInstance().sourceContainer as IDirtyChecker).promptToSave();
		}else{
			Alert.show("Save & Proceed");
		}
		return;
	}else{
		DirtyChecker.getInstance().resetDirtyChecker();
	}
	
	var params:String = "OPERATION=ACTIVITY_GETDETAILS" +
						"&PKID=" + escape(StringUtil.trim(this.key)) +
						"&OWNERID="+CommonClass.UserID;
	
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForActivityDetails);
	ws.addPartnerServiceFaultEventListener(partnerServiceFaultHandler);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.ModuleCvs);
}

private function callForActivityDetails(event:ProcessServiceRequestResultEvent):void{
//	BusySpinner.getInstance().stop();	
	actdetails = XML(event.result);
//	Alert.show(actdetails.toString());
	if(actdetails.RESPONSE.RESULT == "E"){
		Alert.show(actdetails.MESSAGE);
	}else if(actdetails.RESPONSE.RESULT == 'S'){
		setDataOnControls(actdetails);
		setScreenMode();
		typeSelectionChange();
	}
}

private function partnerServiceFaultHandler(event:FaultEvent):void{
//	BusySpinner.getInstance().stop();
	Alert.show(event.fault.toString());
}

private function setDataOnControls(response:XML):void{
	cmbAccountName.dataProvider = new XML(response.ACCOUNTS).entry as XMLList;
//	cmbAccountName.selectedIndex = 0;
//	cmbAccountName.selectedItem = (response.ACCOUNTS.entry.(@id == response.RELATIONS.RELATION.(@type == "ACTIVITY_ACCOUNT"))[0]) as XML;
	
	cmbActivityOwner.dataProvider = new XML(response.USERS).entry as XMLList;
	cmbActivityOwner.selectedIndex = 0;
	cmbActivityOwner.selectedItem = (response.USERS.entry.(@id == response.RELATIONS.RELATION.(@type == "OWNER"))[0]) as XML
	
	cmbActivityType.dataProvider = new XML(response.ACTIVITYTYPE).entry as XMLList;
	cmbActivityType.selectedIndex = 0;
	cmbActivityType.selectedItem = (response.ACTIVITYTYPE.entry.(@id == response.ACTIVITYTYPEID)[0]) as XML

	cmbStatus.dataProvider = new XML(response.STATUS).entry as XMLList;
	cmbStatus.selectedIndex = 0;
	cmbStatus.selectedItem = (response.STATUS.entry.(@id == response.ACTIVITYSTATUSID)[0]) as XML
	
	CommonClass.setDataOnComponents(this.txtActivityName, response);
	CommonClass.setDataOnComponents(this.txtNotes, response);
	CommonClass.setDataOnComponents(this.dtStart, response);
	CommonClass.setDataOnComponents(this.tmStart, response);
	CommonClass.setDataOnComponents(this.dtEnd, response);
	CommonClass.setDataOnComponents(this.tmEnd, response);

	cmbContact.dataProvider = new XML(response.CONTACTS).entry.(@accountid == cmbAccountName.selectedItem.@id) as XMLList;
	cmbContact.selectedIndex = 0;
	cmbContact.selectedItem = (response.CONTACTS.entry.(@id == response.RELATIONS.RELATION.(@type == "PRIMARY_CONTACT"))[0]) as XML	

	if(this.accountGUID.length >0){
		cmbAccountName.selectedItem = (response.ACCOUNTS.entry.(@guid == this.accountGUID.toUpperCase())[0]) as XML;
	}
}

private function onClick(mode:String):void{
	switch(mode){
		case "editdetails":
//			Alert.show("Edit Details");
			frmActivityInfo.enabled = true;
			btnSubmit.enabled = true;
			cmbAccountName.enabled = false;
			cmbActivityOwner.enabled = false;
			_btnEditCancel.enabled = false;
			this.lblTitle.text = "Edit Activity Details";
			break;
	}
}

private function buttonClick(eventType:String):void{
	switch(eventType){
		case "save":
			handleSubmitClick();
			break;
		case "cancel":
			handleCancelClick();
			break;
		default:
			Alert.show( "Yet to Implement : " + eventType);
	}
}

private function handleCancelClick():void{
	(this.parentDocument as CMDWindow).NavInfo = null;
	(this.parentDocument as CMDWindow).loadModule();
}

private function handleSubmitClick():void{
	if(validate()){
		saveData("", getPostData());
	}else{
		Alert.show("Please provide missing/incorrect details before saving","Save");
	}
}

private function getPostData():String{
	var postData:String = new String();
	postData += "ACTIVITYID=" + (actdetails.ACTIVITYID.toString())				+ "&";
	postData += "ACTIVITYGUID=" + (actdetails.ACTIVITYGUID.toString())			+ "&";
	postData += "USERID=" + (CommonClass.UserID)								+ "&";
	postData += "NOTEID=" + (actdetails.NOTEID.toString())						+ "&";
	
	postData += (CommonClass.preparePostString(this.txtActivityName))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbActivityType))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbStatus))					+ "&";
	postData += (CommonClass.preparePostString(this.dtStart))					+ "&";
	postData += (CommonClass.preparePostString(this.tmStart))					+ "&";
	postData += (CommonClass.preparePostString(this.dtEnd))						+ "&";
	postData += (CommonClass.preparePostString(this.tmEnd))						+ "&";
	postData += (CommonClass.preparePostString(this.txtNotes))					+ "&";
	postData += (CommonClass.preparePostString(this.cmbActivityOwner))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbAccountName))			+ "&";
	postData += (CommonClass.preparePostString(this.cmbContact));
	return postData;	
}

private function saveData(action:String, data:String=""):void{
	var params:String = "OPERATION=ACTIVITY_UPDATEDETAILS" +
						(data.length>0?"&":"") +data;
//	Alert.show(params);
	var ws:PartnerService = new PartnerService();
	ws.addprocessServiceRequestEventListener(callForUpdateActivityDetails);
	ws.processServiceRequest(params);
	
//	BusySpinner.getInstance().play(Application.application.parentApplication);
}


private function callForUpdateActivityDetails(event:ProcessServiceRequestResultEvent):void{
	
	var response:XML = XML(event.result);
//	BusySpinner.getInstance().stop();
	
	if(response.RESPONSE.RESULT == "S"){
		DirtyChecker.getInstance().resetDirtyChecker();
		
		var ni:NavigationInfo = new NavigationInfo(actdetails.PKID,MenuConstants.CMD,MenuConstants.MY_ACCOUNT,String(this.cmbAccountName.selectedItem.@guid));
		(Application.application.ModuleCvs.getChildAt(0) as PostLogin).doNavigate(ni);
//		handleCancelClick();
	}else{
		Alert.show( String(response.toString()) );	
	}	
	
}

private function validate():Boolean{
	return 	(accNameV.validate().type == ValidationResultEvent.VALID) && 
			(contactV.validate().type == ValidationResultEvent.VALID) &&
			(nameV.validate().type == ValidationResultEvent.VALID) &&
			(actvityTypeV.validate().type == ValidationResultEvent.VALID) &&
			(statusV.validate().type == ValidationResultEvent.VALID);
}